<?php
class Discussions extends Controller {

	function Discussions()
	{
		parent::Controller();
		$this->users->check();
		$this->load->helper('typography');
	}

	function index()
	{
		$data['query'] = $this->db->query('SELECT *, COUNT(posts.postid) AS count, discussions.id AS did FROM discussions LEFT JOIN users ON discussions.tuser = users.id LEFT JOIN posts ON posts.discussion = discussions.id GROUP BY discussions.title ORDER BY discussions.id DESC');
		$template['content'] = $this->load->view('discussions', $data, TRUE);
		$template['title'] = 'Discussions';
		$this->load->view('template', $template);
		
	}
	function do_newdiscussion() {
		// Insert new discussion into database
		$this->db->set('title', $_POST['title']);
		$this->db->set('tuser', $_POST['user']);
		$this->db->set('topic', auto_typography($_POST['topic']));
		$this->db->set('tdate', now());
		$this->db->insert('discussions'); 
		redirect('discussions');
	}
	function single() {
		$template ['tabs'] = array(
		anchor('discussions', 'Back to all discussions'),
		);
		$data['discussion'] = $this->db->query('SELECT *, discussions.id AS did FROM discussions LEFT JOIN users ON users.id = discussions.tuser WHERE discussions.id = ' . $this->uri->segment(3));
		$data['posts'] = $this->db->query('SELECT * FROM posts LEFT JOIN users ON posts.user = users.id LEFT JOIN discussions ON posts.discussion = discussions.id WHERE discussion = ' . $this->uri->segment(3) . ' 
		ORDER BY postid ASC');
		foreach ($this->db->query("SELECT * FROM discussions WHERE id = " . $this->uri->segment(3))->result() as $row) {
				$template['title'] = $row->title;
			}
		$template['content'] = $this->load->view('single.php', $data, TRUE);
		$this->load->view('template', $template);
		
	}
	function addpost() {
		// Insert post into database
		$this->db->set('pdate', now());
		$this->db->set('user', $_POST['user']);
		$this->db->set('body', auto_typography(auto_link($_POST['body'])));
		$this->db->set('discussion', $_POST['thisdiscussion']);
		$this->db->insert('posts');
		redirect('discussions/single/' . $_POST['thisdiscussion']);
	}
}